package com.fingard.dsp.bank.directbank.cmbunion01;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.security.PrivateKey;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.zip.ZipInputStream;

















import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.directbank.cmbunion01.util.DSAUtil;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.text.SplitHelper;
import com.fingard.text.StringHelper;

public class CMBUnion01Statement extends CMBUnion01Base implements IStatement {

	@Override
	public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm)
			throws Exception {
		RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
		retAts.writeStart();
		String[] unifiedOrderResp = getUnifiedOrderStatement(p_reqQrySttm, retAts);
		String unifiedOrderTotalNum = retAts.totalNum;
		if ("".equals(unifiedOrderTotalNum)) {
			unifiedOrderTotalNum = "0";
		}
		if ("-1".equals(unifiedOrderResp[0])) {
			retAts.writeRespCode("-1");
			retAts.writeRespInfo("统一下单对账单获取失败,原因:" + unifiedOrderResp[1]);
		} else {
			if (retAts.getWrittenRdCount() == 0) {
				retAts.writeRespCode("0");
				String respInfo = unifiedOrderResp[1];
				if (StringHelper.isNullOrEmpty(respInfo)) {
					respInfo = unifiedOrderResp[1];
				}
				retAts.writeRespInfo(respInfo);
			}
			retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(unifiedOrderTotalNum)));
		}

		retAts.writeEnd();
		return retAts;
	}
	public String[] getUnifiedOrderStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) {
		String[] tmpRespHeader = new String[] { "", "" };

		String tmpRespCode = "";
		String tmpRespInfo = "";
		retAts.totalNum = "0";
		int totalNum = 0;
		try{
			ActSetItem actItem = this.getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
			if(actItem != null){
		        String version = "1.0";//版本
		        String service = "cod.pay.bill.download";//服务名

		        JSONObject param  = new JSONObject();
		        param.put("bill_date", p_reqQrySttm.busDate);//对账日期
		        param.put("bank_app_id", "819806210457866240");


		        String strParam = param.toString();
		        Map<String, String> req = new HashMap<String, String>();
		        req.put("params", strParam);
		        req.put("app_id", actItem.merchantId);
		        req.put("version", version);
		        req.put("service", service);


		        String timestamp = String.valueOf(new Date().getTime()/1000);
		        PrivateKey dsaPrivateKey = DSAUtil.loadPrivateKey(actItem.oppCertFilePath,actItem.ownKeyPassword);//加载私钥
		        String sign = this.sign(actItem.merchantId, service, version, timestamp,strParam, dsaPrivateKey);
		        req.put("timestamp", timestamp);
		        req.put("sign", sign);
		        WriteBankLogStep2(req.toString());
		        String bill_date = Format.Date8Format.format(p_reqQrySttm.getBusDate());
		        if(actItem.qryStatementURL==null||"".equals(actItem.qryStatementURL)){
		        	tmpRespCode = "-1";
					tmpRespInfo = "请配置对账单下载地址";
		        }
				String filePath = actItem.qryStatementURL + File.separator + p_reqQrySttm.actNum + "_" + bill_date + ".zip";
				WriteBankLogLn("对账单下载后保存到本地路径:" + filePath);
		        String result=request(req,bankFront.getUrl("downloadbill"),filePath);
		        if(result ==null){
		        	File zip = new File(filePath);
		        	if(zip.length()>100){
		        		StringBuilder content = new StringBuilder();  
			        	readZipFile(filePath,content);
			        	StringReader strReader = new StringReader(content.toString());
						BufferedReader tmpReader = new BufferedReader(strReader);
						String line1 = tmpReader.readLine();
						String[] columns = line1.split(",");
						while (true) {
							String eachline = tmpReader.readLine();
							if (eachline == null || "".equals(eachline)) {
								break;
							}
							
							String[] values = eachline.split(",");
							if(values.length==3){
								continue;
							}
							if(values.length<23){
								values = Arrays.copyOf(values,23);
							}
							

							
							if (columns.length == values.length) {
								HashMap<String, String> mapKV = SplitHelper.splitAsValueMap(columns, values);
								RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
								totalNum++;
								// 每笔明细记录：记账时间,微信支付业务单号,资金流水单号,业务名称,业务类型,收支类型,收支金额（元）,账户结余（元）,资金变更提交申请人,备注,业务凭证号
								if (mapKV.containsKey("订单金额")) {
									tmpRetDetail.amount = StringHelper.amountDivide100(mapKV.get("订单金额").replace("`", ""));
								}
								if (mapKV.containsKey("创建时间")) {
									tmpRetDetail.busTime = mapKV.get("创建时间").replace("`", "").replace("-", "").replace(":", "").replace(" ", "");
								}
								if (mapKV.containsKey("商户订单号")) {
									tmpRetDetail.askNumber = mapKV.get("商户订单号").replace("`", "");
								}
								if (mapKV.containsKey("云订单号")) {
									tmpRetDetail.bkSeq = mapKV.get("云订单号").replace("`", "");
								}
								if (mapKV.containsKey("商户手续费")) {
									tmpRetDetail.fee = StringHelper.amountDivide100(mapKV.get("商户手续费").replace("`", ""));
								}
								if (mapKV.containsKey("支付账号ID")) {
									tmpRetDetail.oppAct = mapKV.get("支付账号ID").replace("`", "");
								}
								tmpRetDetail.transState = TransState.Success;
								tmpRetDetail.cdFlag = "22";
								retAts.writeRetDetail(tmpRetDetail);
							}else{
								continue;
							}
						}
		        	}else{
		        		tmpRespCode = "-1";
						tmpRespInfo = "对账单不存在";
		        	}
		        	
		        }else{
		        	tmpRespCode = "-1";
					tmpRespInfo = "对账单不存在";
		        }
			}else {
				tmpRespCode = "-1";
				tmpRespInfo = "未找到账号[" + p_reqQrySttm.actNum + "]商户配置信息";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRespCode = "-1";
			tmpRespInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		retAts.totalNum = String.valueOf(totalNum);
		tmpRespHeader[0] = tmpRespCode;
		tmpRespHeader[1] = tmpRespInfo;
		return tmpRespHeader;
	}
	
	private static String sign(String app_id, String service, String version, String timestamp, String req,PrivateKey dsaPrivateKey) throws Exception{
        StringBuilder sb = new StringBuilder();
        sb.append(app_id).append(timestamp).append(version).append(service).append(req);

        return DSAUtil.sign(dsaPrivateKey, sb.toString());
    }
	public static String[] delete(int index, String array[]) {
        String[] arrNew = new String[index];
        for (int i = 0; i < index; i++) {
            arrNew[i] = array[i];
        }
        return arrNew;
    }
	public void readZipFile(String file,StringBuilder content) throws Exception {
		ZipFile zip = new ZipFile(file);
		@SuppressWarnings("unchecked")
		Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.getEntries();
	      
	    ZipEntry ze;  
	    while (entries.hasMoreElements()) {  
	        ze = entries.nextElement();  
	        WriteBankLogLn("账单解压后文件列表:" + ze.getName());
	        Scanner scanner = new Scanner(zip.getInputStream(ze), "utf-8");  
            while (scanner.hasNextLine()) {  
                content.append(scanner.nextLine()+"\n");  
            }  
            scanner.close();    
	    } 
	    zip.close();  
	}
 
}
